(function($, _) {
	$.template = {
		tweet : _.template($('#tweetTemplate').text()),
		ustadz : _.template($('#ustadzTemplate').text()),
		mediaLink : _.template($('#mediaLinkTemplate').text()),
		urlEntity : _.template($('#urlEntityTemplate').text()),
		urlLink : _.template($('#urlLinkTemplate').text()),
		imgLink : _.template($('#imgLinkTemplate').text()),
		urlLinkWithTitle : _.template($('#urlLinkWithTitleTemplate').text()),
		hashTagLink : _.template($('#hashTagLinkTemplate').text()),
		tweetPopular : _.template($('#tweetPopularTemplate').text()),
		conversation : _.template($('#convTemplate').text()),
		noConversation : _.template($('#noConvTemplate').text())
	};
	$.constant = {
		appName : "qoola",
		rootURL : window.location.protocol + "//" + window.location.host
	};
	$.fullPath = function(url)  {return  $.constant.rootURL + '/' + $.constant.appName + '/' + url; };
	$.fn.populateWithTemplateItem = function(item, template) {
		var $this = $(this), items = '';					
		for(var i = 0 ; i < item.length; i++)items += template(item[i]);
		$this.html(items);
	};

	$.onClickConversation = function(response, e) {
		var theConvId = e.data.convid;
		var statusID = e.data.statusid;
		var screenName = e.data.screen_name;
		var $convIdDiv = $('#conversation_'+theConvId);
		//window.console && console.debug("onClickConversation " + theConvId);		
		$('#tabs-1 .conv').fadeOut('fast',function(){
			$('#tabs-1 .conv').empty();
			$('#tabs-1 .conv').append('<div class="loader"></div>');
		});
		$.get($.fullPath("getConversations.php")+ "?convid="+theConvId,
		function( data) {
			if ($('#tabs-1 .conv').is(":hidden") ||$('#tabs-1 .conv').size() == 0) { $('#tabs-1 .conv').show(); }
			$('#tabs-1 .conv').fadeOut('fast',function(){
				$('#tabs-1 .conv').empty();
				$('#tabs-1 .conv').append('<div class="loader"></div>');
				var markupconv = '';
				var position = $convIdDiv.position();
				var el_height = $convIdDiv.parent().parent().height();
				for ( var i = 0; i < data.length; i++) {
					//conversion entities
					//include all the links of the entities into the text
					var txt = data[i].text;
					if(data[i].media_url != null && data[i].media_url.length > 0 ){
						for(var k = 0 ; k < data[i].media_url.length; k++){
							var medurl = '<a href="'+data[i].media_expanded_url[k]+'" target="_blank">'
								+ data[i].media_expanded_url[k] +'</a>';
							txt = txt.replace(data[i].text.substr(data[i].media_index_start[k],
								response[i].media_index_end[k]-response[i].media_index_start[k]),medurl);
						}
					}
					if(data[i].url_entity != null && data[i].url_entity.length > 0){
						for(var k = 0 ; k < data[i].url_entity.length; k++){
							var enturl = '<a href="'+data[i].url_entity[k]+'" target="_blank">' 
								+ data[i].url_entity[k] +'</a>';
							//txt = txt.replace(response[i].text.substr(response[i].url_index_start[k],response[i].url_index_end[k] - response[i].url_index_start[k]),enturl);				
							txt = txt.replace(data[i].url_entity[k],enturl);
						}
					}
					if(data[i].hashtag_text != null && data[i].hashtag_text.length > 0){
						for(var k = 0 ; k < data[i].hashtag_text.length; k++){
							if(response[i] == null || response[i].hashtag_text == null || response[i].hashtag_text[k] == null){
								continue;
							}
							var enturl = '<a href="http://twitter.com/\#!/search/%23'+response[i].hashtag_text[k]+'" target="_blank">'
								+ '#'+data[i].hashtag_text +'</a>';
							//txt = txt.replace(response[i].text.substr(response[i].hash_start[k],response[i].hash_end[k]-response[i].hash_start[k]),enturl);
							if(txt != null && txt.length > 0){
								txt = txt.replace('#'+data[i].hashtag_text[k],enturl);
							}
						}
					}
					if(data[i].mentioned_screen_name != null){
						for(var k = 0 ; k < data[i].mentioned_screen_name.length ; k++){
							/*	var mentioned = '<a href="http://twitter.com/\#!/'+data[i].mentioned_screen_name[k]+'" target="_blank">'
								+ '@'+data[i].mentioned_screen_name[k] +'</a>';*/
							var mentioned = '@'+data[i].mentioned_screen_name[k];
							//txt = txt.replace(response[i].text.substr(response[i].mention_start[k],response[i].mention_end[k]-response[i].mention_start[k]),mentioned);
							if(txt != null && txt.length > 0){
								txt = txt.replace('@'+data[i].mentioned_screen_name[k],mentioned);
							}											
						 }
					}
					//------------------------------------
					//Include all the entities into the tweet
					var entities = [];
					if(data[i].url_entity != null && data[i].url_entity.length > 0){
						for(var k = 0 ; k < data[i].url_entity.length; k++){
							entities.push(data[i].expanded_url[k] != null ? data[i].expanded_url[k] : data[i].url_entity[k]);
						}
					} 
					var medias = [];
					if(data[i].media_url != null && data[i].media_url.length > 0){
						for(var k = 0 ; k < data[i].media_url.length; k++){
							medias.push({url : data[i].media_url[k], width : data[i].size_small_w[k], height : data[i].size_small_h[k]});	
						}
					}
					//-----------------------------------------
					markupconv += $.template.conversation({ isTop : (i == 0), is_ustadz : data[i].is_ustadz, 
						topPosition : 0, text : txt, profile_img_url : data[i].profile_img_url, 
						name : (data[i].name != undefined && data[i].name != null) ? data[i].name : data[i].display_name, screen_name: data[i].screen_name,
						medias : medias, entities : entities, created_at : data[i].created_at, status_id :data[i].statusid
						});
					/*$(document).on('click','#reply_' + data[i].statusid,  { 
						convid : data[i].convid
						, statusid : data[i].statusid
						, screen_name : data[i].screen_name}
						, function(e) {
							$("#reply_dialog_modal").dialog({
								width: 400,
								modal: true,
								title: "Kirim Komentar",
								open : function(event, ui){
									$("#reply_dialog_modal").empty();
									twttr.anywhere(function (T) {
									    T("#reply_dialog_modal").tweetBox({
									        width: 350,
									        label: "",
									        closeText: 'Tutup',
									        defaultContent: "@"+e.data.screen_name,
									        data: {in_reply_to_status_id : e.data.statusid},
									        onTweet: function(plainText,htmlText){
									        			$("#reply_dialog_modal").dialog('close');
									        		}
									      });
									 });
									
								}
							});
						});*/
				}
				markupconv += '<div class="tweet_conv"><div class="triangle-border right"><div id="conv_comment_box"></div><div style="clear: both;"></div></div>';
				
				//markupconv += '</div>';
				if(data.length == 0){
					markupconv = $.template.noConversation({topPosition : (position.top-(el_height*0.8))});
				}
				$('#tabs-1 .conv').empty();
				$('#tabs-1 .conv').append(markupconv);
				var dwidth = $('.page').width();
				$(".tweet_conv").width(34*dwidth/100);
				$('#tabs-1 .conv').fadeIn('slow',function(){
					twttr.anywhere(function (T) {
						//alert(statusID);
					    T("#conv_comment_box").tweetBox({
					        height: 50,
					        width: $(".triangle-border").width(),
					        label: "Kirim Komentar",
					        defaultContent: "@"+screenName,
					        data: {in_reply_to_status_id : statusID}
					      });
					 });
					twttr.anywhere(function (T) {
						T('#tabs-1 .conv').hovercards({ expanded: true });
					});
					
				
				});
			});
		}, "json");				
	};		

	$.fn.updateTweetList = function() {
		//window.console && console.debug ("update tweet list");
		var $this = $(this);
		//$this.doTimeout( 'tweet_list'); //stop timeout.
			
		$this.autobrowse({
				url : function(offset) {
					return $.fullPath("getPopularTweets.php") + "?start=OFFSET"
							.replace(/OFFSET/, offset);
				},
				refresh: false,
				urlRefresh : function(currentOffset) {
					return $.fullPath("getPopularTweets.php") + "?start=0&currentOffset=OFFSET"
							.replace(/OFFSET/, currentOffset);
				},				
				refreshRate : 8000,
				template : function(response) {				
					var markup = "";								
					for ( var i = 0; i < response.length; i++) {
						var txt = response[i].text;	
						if(response[i].media_url != null){						
								for(var k = 0 ; k < response[i].media_url.length; k++){
									var medurl = $.template.mediaLink({url: response[i].media_expanded_url[k]}); 
									txt = txt.replace(response[i].text.substr(response[i].media_index_start[k],response[i].media_index_end[k]-response[i].media_index_start[k]),medurl);
								}
						}
						if(response[i].url_entity != null){
								for(var k = 0 ; k < response[i].url_entity.length; k++){
									var enturl = $.template.urlLink({url: response[i].url_entity[k]});
									txt = txt.replace(response[i].url_entity[k],enturl);
								}
						}
						if(response[i].hashtag_text != undefined && response[i].hashtag_text != null){
								for(var k = 0 ; k < response[i].hashtag_text.length; k++){
									var enturl = $.template.hashTagLink({url: response[i].hashtag_text[k]});
									txt = txt.replace('#'+response[i].hashtag_text[k],enturl);
								}
						}
						if(response[i].mentioned_screen_name != null){		
								for(var k = 0 ; k < response[i].mentioned_screen_name.length ; k++){
									var mentioned = '@'+response[i].mentioned_screen_name[k];
									txt = txt.replace('@'+response[i].mentioned_screen_name[k],mentioned);								
								}
						}
						//------------------------------------
						//Include all the entities into the tweet
						var entities = [];
						if(response[i].url_entity != null && response[i].url_entity.length > 0){
							for(var k = 0 ; k < response[i].url_entity.length; k++){
								entities.push({url_entity: response[i].url_entity[k], page_title : response[i].page_title[k],
									noembed_title: response[i].noembed_title[k], fb_thumbnail_url : response[i].fb_thumbnail_url[k],
									noembed_thumbnail_url : response[i].noembed_thumbnail_url[k], page_image : response[i].page_image[k],
									fb_page_desc : response[i].fb_page_desc[k],page_image : response[i].page_image[k],
									page_desc : response[i].page_desc[k], expanded_url : response[i].expanded_url[k]
								});
							}
						} 
						var medias = [];
						if(response[i].media_url != null && response[i].media_url.length > 0){
							for(var k = 0 ; k < response[i].media_url.length; k++){
								medias.push({url : response[i].media_url[k], width : response[i].size_small_w[k], 
								height : response[i].size_small_h[k]});	
							}
						}
						//-----------------------------------------
						
						markup += $.template.tweetPopular({ text : txt,
							profile_img_url : response[i].profile_img_url, name : response[i].name, display_name : response[i].display_name, screen_name : response[i].screen_name,
							medias : medias, entities : entities, created_at : response[i].created_at,
							convid : response[i].convid, convid_count: response[i].convid_count, status_id : response[i].statusid
							});
						$('#conversation_' + response[i].convid).off();
						$(document).on('click','#conversation_' + response[i].convid,  { convid : response[i].convid
																						, statusid : response[i].statusid
																						, screen_name : response[i].screen_name}
																						, function(e) {$.onClickConversation(response, e);});
						/*$(document).on('click','#reply_' + response[i].statusid,  { 
							convid : response[i].convid
							, statusid : response[i].statusid
							, screen_name : response[i].screen_name}
							, function(e) {
								$("#reply_dialog_modal").dialog({
									width: 400,
									modal: true,
									title: "Kirim Komentar",
									open : function(event, ui){
										$("#reply_dialog_modal").empty();
										twttr.anywhere(function (T) {
										    T("#reply_dialog_modal").tweetBox({
										        width: 350,
										        label: "",
										        closeText: 'Tutup',
										        defaultContent: "@"+e.data.screen_name,
										        data: {in_reply_to_status_id : e.data.statusid},
										        onTweet: function(plainText,htmlText){
										        			$("#reply_dialog_modal").dialog('close');
										        		}
										      });
										 });
										
									}
								});
							});*/
               }		
				//window.console && console.debug ("finish templating.");
					
					return markup;
				},
				itemsReturned : function(response) {
					//if(response.length == 0) window.console && console.debug ("there's no item returned.");
					return response.length;
				},
				max : 1000,
				sensitivity : 100,
				finished : function() {
					$(this).append('<p style="text-align:center">Semua telah ditampilkan.</p>');
				},
				complete: function(){
					twttr.anywhere(function (T) {
						T('#tabs-1 .items').hovercards({ expanded: true });
					});
				}
		});
		
	};
	$.getJSON($.fullPath("getTopRank.php"),
		function(data) {
			//window.console && console.debug("populate data after getTopRank");
			var toptweets = data.top_tweet;
			$('#topTweetList').populateWithTemplateItem(data.top_tweet, $.template.tweet);
			$('#topUstadzList').populateWithTemplateItem(data.top_ustadz, $.template.ustadz);
	});
	var trending_refresh_handler = function(){
		$("#trending_refresh").off();
		$(".items").empty();
		$('.conv').empty();
		$('.tweet_action').off();
		$('.items').updateTweetList();
		$("#trending_refresh").click(trending_refresh_handler);
	};
	
	
	
	$("#trending_refresh").click(trending_refresh_handler);
	$('#tabs-1 .conv').fadeIn('fast');
})(jQuery, _);
